import React, { Component } from 'react';
import { InputNumber } from 'antd';
import { Button,Popconfirm,Tag,Space } from 'antd';
import { DeleteOutlined,UploadOutlined} from '@ant-design/icons';
import AddWeightFormModal from './AddWeightFormModal';
import axios from 'axios';

/**
 * 成绩系数输入
 */
class WeightSetter extends Component {
    constructor(props) {
        super(props);
        this.query = this.props.location.query;//传入的参数
        //测试数据,防止每次刷新都无数据导致报错
        if (!this.query) {
            this.query = {
                "_id": "5f4e1da702e91822e86f38d8",
                "courseid": "5.1",
                "coursenumber": "5",
                "coursekind": "必修课",
                "coursename": "软件设计与体系结构",
                "teachernumber": "5",
                "assessmentmethod": "考试",
                "classlist": [
                    "2017240206",
                    "2017240207"
                ],
                "term": "2020-2021第一学期",
                "status": 0,
                "gradepecents": {
                    '考试成绩': 0.7,
                    '平时成绩': 0.3,
                }
            }
        }
        //在这里设置api
        this.onSubmit = this.query.onSubmit||((params)=>{
            params = JSON.stringify(params);
            return axios.post('http://localhost:8989/user/addgradepecents',params,{
                headers: {
                    "Content-Type": "application/json;charset=utf-8"
                }
            });
        })

        this.state = {
            courseid :this.query.courseid,
            term:this.query.term,
            gradepecents: this.query.gradepecents || {},//成绩系数
            weightKeys:{},
            onSubmit:this.onSubmit,//function (data)返回Promise对象
        }
        this.nextKey=1;
        //为每个成绩系数分配key值
        for(let weightName in this.state.gradepecents){
            this.state.weightKeys[weightName]=this.getNextKey();//生成key值
        }
        

    }

    getNextKey=()=>{
        return this.nextKey++;
    }

    /**
     * 处理输入框改变，输入框数值改变时，修改state中的成绩系数值
     * @param {系数名} weightName 
     * @param {当前值} value 
     */
    handleInputChange=(weightName,value)=>{
        let curState = this.state;
        curState.gradepecents[weightName]=Number(value);
        this.setState(curState);
    }



    /**
     * 添加成绩系数
     * @param {成绩系数名} weightName 
     */
    addWeight = (weightName) => {
        if(weightName in this.state.gradepecents) return;//如果已经存在则返回
        
        this.setState((state) => {
            state.gradepecents[weightName]=0;
            state.weightKeys[weightName] = this.getNextKey();//为新生成的成绩系数生成key
            return state;
        })
    }

    /**
     * 删除成绩系数
     * @param {成绩系数名} weightName 
     */
    removeWeight = (weightName) =>{
        if(!(weightName in this.state.gradepecents)) return;//如果不存在，则返回
        this.setState((state) => {
            delete state.gradepecents[weightName];
            delete state.weightKeys[weightName];
            return state;
        })
    } 

    /**
     * 提交对成绩系数的改变
     */
    submitChange=()=>{
        let data = {
            gradepecents:this.state.gradepecents,
            courseid:this.state.courseid,
            term:this.state.term,
        }
        //判断合法性
        let sum=0;
        for(let key in data.gradepecents){
            sum += data.gradepecents[key];
        }
        if(sum !== 1.0){
            alert('成绩系数总和必须为100%，当前和为：'+sum*100+'%');
            return;
        }

        this.state.onSubmit(data)
        .then((msg)=>msg==='OK'?alert('修改成功'):alert('修改失败'))
        .catch((msg)=>alert('数据提交失败'));
        
    }


    render() {
        return (
            <Space direction="vertical" align="center">
                {Object.keys(this.state.gradepecents).map(
                    (weightName) => {
                        let key = this.state.weightKeys[weightName];
                        return (
                            <div>
                            <Space align="center">
                                <Tag color="blue">{weightName}</Tag>
                                <InputNumber
                                    key={key}
                                    
                                    defaultValue={this.state.gradepecents[weightName]}
                                    min={0}
                                    step={0.05}
                                    max={1}
                                    formatter={value => `${value*100}%`}
                                    parser={value => value.replace('%', '')/100}
                                    onChange={(value)=>this.handleInputChange(weightName,value)}
                                />
                                <Popconfirm
                                    key={-key}
                                    title={'你确定要删除成绩系数【'+weightName+'】吗？未提交修改之前，不会真正修改，退出此页即可撤销。'}
                                    onConfirm={()=>this.removeWeight(weightName)}
                                    okText="是"
                                    cancelText="否"
                                    placement='right'
                                >   
                                
                                    <Button 
                                        
                                        icon={<DeleteOutlined />}
                                        //onClick={()=>this.removeWeight(weightName)}//如果去掉注释，则是直接删除，不询问
                                        shape="round"
                                        danger
                                    >
                                        删除
                                    </Button>
                                </Popconfirm>
                            </Space>
                            </div>
                        );
                    }


                )}
                <div>
                    <AddWeightFormModal onCreate={this.addWeight}/>
                </div>
                <div>
                    <Button 
                        type="primary"
                        icon={<UploadOutlined />}
                        onClick={(e)=>this.submitChange(e)}
                        shape='round'
                    >
                        提交
                    </Button>
                    
                </div>
            </Space>
        );
    }
}

export default WeightSetter;